// Copyright (c) Appeon. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. 
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.

using System;
using System.Data;
using System.Linq;
using System.Text;

namespace SnapObjects.Data.Oracle
{
    internal class OracleSqlFunctionStatementGenerator : SqlFunctionStatementGenerator
    {
        public OracleSqlFunctionStatementGenerator(
            ISqlStatementFactory factory,
            ISqlGenerationHelper helper,
            ITypeMapper typeMapper) : base(factory, helper, typeMapper)
        {
        }

        public override SqlSyntaxDescription Create(SqlStatement statement)
        {
            var function = (SqlFunctionStatement)statement;

            var outParam = function.Parameters.FirstOrDefault(
                m => m.Value.Direction == ParameterDirection.Output || 
                m.Value.Direction == ParameterDirection.InputOutput || 
                m.Value.Direction == ParameterDirection.ReturnValue);

            if (String.IsNullOrWhiteSpace(outParam.Key))
            {
                return base.Create(statement);
            }

            return this.InternalCreate(function);
        }

        protected override void CreateFrom(
            StringBuilder sqlBuilder, SqlStatement statement, string functionName)
        {
            var function = (SqlFunctionStatement)statement;

            if (function.ReturnType == FunctionReturnType.Scalar)
            {
                sqlBuilder.Append(SqlWhitespaceToken.Whitespace);
                sqlBuilder.Append(new SqlKeywordToken(SqlKeywords.FROM));
                sqlBuilder.Append(SqlWhitespaceToken.Whitespace);
                sqlBuilder.Append("DUAL");
            }
            else
            {
                sqlBuilder.Append(SqlWhitespaceToken.Whitespace);
                sqlBuilder.Append(new SqlKeywordToken(SqlKeywords.FROM));
                sqlBuilder.Append(SqlWhitespaceToken.Whitespace);
                sqlBuilder.Append(functionName);

                this.CreateParameters(sqlBuilder, statement);
            }
        }

        private SqlSyntaxDescription InternalCreate(SqlFunctionStatement function)
        {
            var tokens = this.SpliceStatement(function);

            var builder = new StringBuilder();

           foreach (var token in tokens)
            {
                if (token.Type == SqlTokenType.Identifier)
                {
                    builder.Append(_helper.DelimitIdentifier(token.Text));
                }
                else
                {
                    builder.Append(token.Text);
                }
            }

            var isFirstParameter = true;

            foreach (var parameter in function.Parameters)
            {
                if (parameter.Value.Direction == ParameterDirection.ReturnValue)
                {
                    builder.Insert(0, " := ");
                    builder.Insert(0, ":" + parameter.Value.Name);
                }
                else
                {
                    if (!isFirstParameter)
                    {
                        builder.Append(",");
                    }
                    else
                    {
                        builder.Append(SqlCharacters.OpenParentheses);
  
                        isFirstParameter = false;
                    }

                    builder.Append(SqlWhitespaceToken.Whitespace);
                    builder.Append(":" + parameter.Value.Name);
                }
            }

            builder.Insert(0, "begin ");

            if (isFirstParameter)
            {
                builder.Append(SqlCharacters.OpenParentheses);
            }

            builder.Append(SqlCharacters.CloseParentheses);
            builder.Append(_helper.StatementTerminator);

            builder.Append(" end");
            builder.Append(_helper.StatementTerminator);

            var parameters = function.Parameters.ToDictionary(
                m => m.Key, m => _helper.GenerateParameterName(m.Key));

            return new SqlSyntaxDescription(builder.ToString(), parameters, true);
        }
    }
}
